package cn.edu.zafu.bigdata.xct.wlbc;

import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class UDPTimeServer {
    public static void main(String[] args) {
        int serverPort = 12345; // 设置服务端的端口号
        try (DatagramSocket serverSocket = new DatagramSocket(serverPort)) {
            byte[] receiveData = new byte[1024];
            byte[] sendData = new byte[1024];

            System.out.println("服务端启动，等待客户端请求...");

            while (true) {
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                serverSocket.receive(receivePacket);
                String sentence = new String(receivePacket.getData(), 0, receivePacket.getLength());
                System.out.println("收到请求: " + sentence);

                // 获取当前时间
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String currentTime = sdf.format(new Date());

                // 发送时间给客户端
                InetAddress IPAddress = receivePacket.getAddress();
                int clientPort = receivePacket.getPort();
                sendData = currentTime.getBytes();
                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, clientPort);
                serverSocket.send(sendPacket);
                System.out.println("发送时间: " + currentTime);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}